package com.corn.flink.lesson5;

import com.corn.flink.lesson4.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;

/**
 * global window process
 *
 * @author JimWu
 * @date 2023/3/13 18:07
 **/
public class WindowProcessFunctionDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<Event> ds = env.fromElements(
                new Event("add", 1000),
                new Event("delete", 2000),
                new Event("update", 3000),
                new Event("select", 5000),
                new Event("add", 6000),
                new Event("delete", 7000),
                new Event("select", 8000),
                new Event("select", 9000),
                new Event("select", 10000),
                new Event("select", 11000)
        );

        ds.assignTimestampsAndWatermarks(
                WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                            @Override
                            public long extractTimestamp(Event element, long recordTimestamp) {
                                return element.timestamp;
                            }
                        }))
                .keyBy(data -> data.type)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new MyProcessFunction())
                .print();

        env.execute();
    }

    static class MyProcessFunction extends ProcessWindowFunction<Event, Map<String, Integer>, String, TimeWindow> {
        @Override
        public void process(String s, Context context, Iterable<Event> elements, Collector<Map<String, Integer>> out) throws Exception {
            HashMap<String, Integer> result = new HashMap<>();
            Iterator<Event> it = elements.iterator();
            while (it.hasNext()) {
                Event event = it.next();
                Integer amount = Optional.ofNullable(result.get(event.getType())).orElse(0);
                amount++;
                result.put(event.getType(), amount);
            }
            System.out.println(new Timestamp(context.window().getStart()));
            out.collect(result);
            System.out.println(new Timestamp(context.window().getEnd()));
        }
    }
}
